package com.sdkdjn.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sdkdjn.mapper.AccessRecordMapper;
import com.sdkdjn.mapper.ManagerMapper;
import com.sdkdjn.mapper.StudentMapper;
import com.sdkdjn.pojo.AccessRecord;
import com.sdkdjn.pojo.AccessRecordExample;
import com.sdkdjn.pojo.Manager;
import com.sdkdjn.pojo.ManagerExample;
import com.sdkdjn.pojo.Student;
import com.sdkdjn.pojo.StudentExample;
import com.sdkdjn.pojo.StudentExample.Criteria;
import com.sdkdjn.service.IIEGService;
import com.sdkdjn.utils.HttpUtil;
import com.sdkdjn.utils.IEGResult;
import com.sdkdjn.utils.JsonUtils;
import com.sdkdjn.utils.MD5Utils;
import com.sdkdjn.utils.PageBean;

/**
 * 智能门禁系统Service
 * @ClassName: IEGServiceImpl  
 * @Description: TODO  
 * @author xiaoshengfu(2439323118@qq.com)  
 * @date: 2018年5月24日 下午9:14:01
 */
@Service
public class IEGServiceImpl implements IIEGService {

	@Autowired
	private AccessRecordMapper accessRecordMapper;
	@Autowired
	private ManagerMapper managerMapper;
	@Autowired
	private StudentMapper studentMapper;

	private String accessToken = "24.f24be9923c1baf0006c2f3a444cf737f.2592000.1530004615.282335-11231888";

	@Override
	public void studentAccess(AccessRecord accessRecord) {
		accessRecordMapper.insertSelective(accessRecord);
	}

	@Override
	public PageBean<Student> studentList(int pageNum, int limit, String sort, String order, String search) {
		PageHelper.startPage(pageNum, limit);
		StudentExample sdtudentExample = new StudentExample();
		sdtudentExample.setOrderByClause(sort + " " + order);
		Criteria criteria = sdtudentExample.createCriteria();
		if (StringUtils.isNotBlank(search)) {
			criteria.andStudentNumberEqualTo(search);
		}
		List<Student> list = studentMapper.selectByExample(sdtudentExample);
		PageInfo<Student> pageInfo = new PageInfo<Student>(list);
		PageBean<Student> pageBean = new PageBean<Student>(limit, pageInfo.getTotal(), pageNum, list);
		return pageBean;
	}

	@Override
	public IEGResult addStudent(Student student) {
		int i = studentMapper.insertSelective(student);
		if (i == 1) {
			String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add";
			try {
				Map<String, Object> map = new HashMap<>();
				Map<String, Object> studentMap = new HashMap<>();
				studentMap.put("name", student.getName());
				studentMap.put("sex", student.getSex());
				studentMap.put("roomNumber", student.getRoomNumber());
				studentMap.put("major", student.getMajor());
				map.put("image", "https://image.wujiantao.cn/" + student.getPictureUrl());
				map.put("group_id", "student");
				map.put("user_id", student.getId());
				map.put("user_info", JsonUtils.objectToJson(studentMap));
				map.put("liveness_control", "NONE");
				map.put("image_type", "URL");
				map.put("quality_control", "LOW");
				String param = JsonUtils.objectToJson(map);
				HttpUtil.post(url, accessToken, "application/json", param);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return IEGResult.iEGResultOK(student);
		}
		return IEGResult.iEGResultError("添加信息失败！");
	}

	@Override
	public PageBean<AccessRecord> accessRecordList(int pageNum, int limit, String sort, String order, String search) {
		PageHelper.startPage(pageNum, limit);
		AccessRecordExample accessRecordExample = new AccessRecordExample();
		accessRecordExample.setOrderByClause(sort + " " + order);
		com.sdkdjn.pojo.AccessRecordExample.Criteria criteria = accessRecordExample.createCriteria();
		if (StringUtils.isNotBlank(search)) {
			criteria.andAccessTimeEqualTo(null);
		}
		List<AccessRecord> list = accessRecordMapper.selectByExample(accessRecordExample);
		PageInfo<AccessRecord> pageInfo = new PageInfo<AccessRecord>(list);
		PageBean<AccessRecord> pageBean = new PageBean<AccessRecord>(limit, pageInfo.getTotal(), pageNum, list);
		return pageBean;
	}

	@Override
	public IEGResult managerLogin(String telephone, String password) {
		ManagerExample managerExample = new ManagerExample();
		com.sdkdjn.pojo.ManagerExample.Criteria criteria = managerExample.createCriteria();
		criteria.andTelephoneEqualTo(telephone).andPasswordEqualTo(MD5Utils.md5(password));
		List<Manager> list = managerMapper.selectByExample(managerExample);
		if (list.size() != 0) {
			return IEGResult.iEGResultOK(list.get(0));
		}
		return IEGResult.iEGResultError("账号或密码错误！");
	}

	@Override
	public IEGResult controlIEG(Integer state) {
		return null;
	}

	@Override
	public IEGResult updateStudent(Student student) {
		studentMapper.updateByPrimaryKeySelective(student);
		student = studentMapper.selectByPrimaryKey(student.getId());
		String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/update";
		try {
			Map<String, Object> map = new HashMap<>();
			map.put("image", student.getPictureUrl());
			map.put("group_id", "student");
			map.put("user_id", student.getId());
			map.put("user_info", JsonUtils.objectToJson(student));
			map.put("liveness_control", "NONE");
			map.put("image_type", "URL");
			map.put("quality_control", "LOW");
			String param = JsonUtils.objectToJson(map);
			HttpUtil.post(url, accessToken, "application/json", param);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return IEGResult.iEGResultOK(null);
	}

	@Override
	public IEGResult deleteStudent(Long id) {
		Student student = new Student();
		student.setId(id);
		student.setIsDelete(true);
		studentMapper.updateByPrimaryKeySelective(student);
		return IEGResult.iEGResultOK(null);
	}

	@Override
	public IEGResult findStudentByStudentId(Long studentId) {
		Student student = studentMapper.selectByPrimaryKey(studentId);
		if (student != null) {
			return IEGResult.iEGResultOK(student);
		}
		return IEGResult.iEGResultError("无效学号！");
	}

	@Override
	public List<AccessRecord> getAccessRecordList(Integer time, Integer buildingNumber, Integer state) {
		Date date = null;
		Calendar c = Calendar.getInstance();
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		c.set(Calendar.MILLISECOND, 0);
		if (time == 2) {
			date = new Date(c.getTimeInMillis() - 259200000);
		} else if (time == 3) {
			date = new Date(c.getTimeInMillis() - 604800000);
		} else {
			date = new Date(c.getTimeInMillis());
		}
		AccessRecordExample accessRecordExample = new AccessRecordExample();
		com.sdkdjn.pojo.AccessRecordExample.Criteria criteria = accessRecordExample.createCriteria();
		criteria.andAccessTimeBetween(date, new Date());
		if (state != 0) {
			criteria.andTypeEqualTo(state);
		}
		accessRecordExample.setOrderByClause("access_time desc");
		List<AccessRecord> list = accessRecordMapper.selectByExample(accessRecordExample);
		AccessRecord accessRecord = null;
		Student student = null;
		for (int i = 0; i < list.size(); i++) {
			accessRecord = list.get(i);
			student = studentMapper.selectByPrimaryKey(accessRecord.getStudentId());
			if (student != null) {
				if (buildingNumber != 0) {
					if (buildingNumber.toString().equals(student.getRoomNumber().split("#")[0])) {
						accessRecord.setStudent(student);
					} else {
						list.remove(i);
						--i;
					}
				} else {
					accessRecord.setStudent(student);
				}
			}
		}
		return list;
	}

	@Override
	public AccessRecord findAccessRecordById(Long id) {
		AccessRecord accessRecord = accessRecordMapper.selectByPrimaryKey(id);
		if (accessRecord != null) {
			accessRecord.setStudent(studentMapper.selectByPrimaryKey(accessRecord.getStudentId()));
		}
		return accessRecord;
	}
}
